package com.breeze.webview.mainprocess;

import android.os.RemoteException;
import android.util.Log;

import com.breeze.webview.ICommandInterface;
import com.breeze.webview.IWebViewProcessCallbackInterface;
import com.breeze.webview.command.WebViewCommand;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * 采用命令模式处理命令，使其符合OCP
 */
public class MainProcessCommandManager extends ICommandInterface.Stub {
    private static final String TAG = "MainProcessCommandManag";
    private static MainProcessCommandManager sInstance;
    private Map<String, WebViewCommand> mCommands = new HashMap<>();

    public static MainProcessCommandManager getInstance() {
        if (sInstance == null) {
            sInstance = new MainProcessCommandManager();
        }
        return sInstance;
    }

    private MainProcessCommandManager() {
        // 加载所有实现了WebViewCommand接口的命令
        ServiceLoader<WebViewCommand> serviceLoader = ServiceLoader.load(WebViewCommand.class);
        for (WebViewCommand command : serviceLoader) {
            if (!mCommands.containsKey(command.name())) {
                mCommands.put(command.name(), command);
            }
        }
    }

    @Override
    public void executeCommand(String command, String params, IWebViewProcessCallbackInterface callback) throws RemoteException {
        executeCommand(command, new Gson().fromJson(params, Map.class), callback);
    }

    private void executeCommand(String command, Map<String, String> params, IWebViewProcessCallbackInterface callback) {
        if (mCommands.containsKey(command)) {
            mCommands.get(command).execute(params, callback);
        } else {
            Log.e(TAG, "executeCommand: 无法处理该请求");
        }
    }
}
